HackerRank Bigger is Greater
https://www.hackerrank.com/challenges/bigger-is-greater/problem
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
from itertools import permutations
#
# Complete the 'biggerIsGreater' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING w as parameter.
#
def biggerIsGreater(w):
# Write your code here
lst = ''.join(p) for p in permutations(w)
lst.sort()
if (lst-1 == w):
return "no answer"
return lstlst.index(w) + 1
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
T = int(input().strip())
for T_itr in range(T):
w = input()
result = biggerIsGreater(w)
fptr.write(result + '\n')
fptr.close()
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'biggerIsGreater' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING w as parameter.
#
def biggerIsGreater(w):
# Write your code here
result = ''
n = len(w)
w = list(w)
i = n - 2
# break point
while i >= 0 and wi >= wi+1:
i -= 1
if i == -1:
result = "no answer"
else:
j = n - 1
while j >= i and wj <= wi:
j -= 1
wi, wj = wj, wi
w = "".join(w)
result = w:i+1 + wi+1:::-1
# dkhc
# else, i=d(0) and j=c(3)(last char)
# d > c, d < h
# after swap: hkdc
# after (i(0)+1~)reverse: hcdk
# hefg
# else, i=f(3) and j=g(3)(last char)
# after swap: hegf
# after (i(3)+1~)reverse: hegf
return result
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
T = int(input().strip())
for T_itr in range(T):
w = input()
result = biggerIsGreater(w)
fptr.write(result + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=Aryt5q_eNfw